import {Log} from "./Log";
import {sdf, MapString} from "./public/sdf";

export class TimeOut {
    static timeMap: MapString<NodeJS.Timer> = {};

    /**
     * 添加延时事件
     * @param time 延时,毫秒
     * @param func 普通函数或async函数
     * @returns {string}事件id
     */
    static add(time: number, func: ()=>(void | Promise<void>)): string {
        let id = sdf.getUniqueId();
        let t = setTimeout(()=> {

            try {
                var ret = <Promise<void>>func();

                if (ret instanceof Promise) {
                    ret.then(()=> {
                        // console.error("Promise then");
                        delete TimeOut.timeMap[id];
                    }).catch(e=> {
                        delete TimeOut.timeMap[id];
                        Log.write("TimeOut Promise", e);
                    });
                }
                else {
                    delete TimeOut.timeMap[id];
                }
            } catch (e) {
                delete TimeOut.timeMap[id];
                Log.write("TimeOut Exception", e);
            }

        }, time);
        TimeOut.timeMap[id] = t;
        return id;
    }

    static remove(id: string): boolean {
        let t = TimeOut.timeMap[id];
        if (t) {
            clearTimeout(t);
            delete TimeOut.timeMap[id];
            return true;
        }
        return false;
    }
}